package com.whfc.wxmp.interceptor;

import com.whfc.common.result.ResultEnum;
import com.whfc.wxmp.annotation.CurrentWxUser;
import com.whfc.fuum.entity.WxUser;
import com.whfc.wxmp.jwt.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class JwtInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String authHeader = request.getHeader("Authorization");
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("{\"code\":"+ ResultEnum.AUTHC_ERROR.getCode()+",\"msg\":\"未登录或token缺失\"}");
            return false;
        }
        String token = authHeader.substring(7);
        try {
            Claims claims = JwtUtil.parseToken(token);
            // 可将claims信息放入request属性，供Controller使用
            request.setAttribute("jwtClaims", claims);

            return true;
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("{\"code\":"+ ResultEnum.AUTHC_ERROR.getCode()+",\"msg\":\"token无效或已过期\"}");
            return false;
        }
    }
}